<?php
/**
 * 用户登陆API
 *
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

class EmployeeController extends BaseController {

	public function index()
	{
		$Mdo = D("Admin/User");
		$ulist = null;
		$wheres = array();

		$role = I('get.role', -1,'intval');
		$sector = I('get.sector', -1, 'intval');
		$status = I('get.status', '-2','intval');
		$ename = I('get.ename','','trim');
		$eyggh = I('get.eyggh',0,'intval');
		$estatus = I('get.estatus',-1,'intval');
		$sex = I('get.sex',-1,'intval');
		$exl = I('get.exl',-1,'intval');
		$eduContent = I('get.eduContent','','trim');
		$ezzmm = I('get.ezzmm',-1,'intval');
		$sector = I('get.sector', -1,'intval');
		$psize = I('get.psize', $this->$m_psize,'intval');

		if (!$psize)
			$psize = $this->m_psize;
		else if ( $psize > 20 )
			$psize = $this->m_psize;
		$wheres['_string'] = "1=1";
		//超级管理员无法在列表中编辑
		if( 1 != $this->m_user['user_id']){
			$wheres['user.user_id'] = array('neq', 1);
		}

		if($ename) {
			$wheres['ext_name'] = array('like','%'.$ename.'%');
		}
		if($eyggh) {
			$wheres['ext_yggh'] = array('eq',$eyggh);
		}
		if(-1 != $estatus) {
			$wheres['ext_user_status'] = array('eq',$estatus);
		}
		if(-1 != $sex) {
			$wheres['user.sex'] = array('eq',$sex);
		}
		if(-1 != $exl){
			$wheres['ext_xl'] = array('eq',$exl);
		}
		if($eduContent) {
			$wheres['edu_content'] = array('like','%'.$eduContent.'%');
		}
		if(-1 != $ezzmm) {
			$wheres['ext_zzmm'] = array('eq',$ezzmm);
		}
		// $sidArr = array();
		// if(-1 != $sector) {
		// 	if($sector != 1){
		// 		$sidArr = array($sector);
		// 		$ziId = M('sector')->where('parent_sector='.$sector)->field('sector_id')->select();
		// 		// dump($ziId);
		// 		if($ziId){
		// 			foreach ($ziId as  $value) {
		// 				foreach ($value as $key => $val) {
		// 					array_push($sidArr,$value[$key]);
		// 				}
		// 			}	
		// 		}
		// 		// $wheres['user.sector_id'] = array('eq' , $sector);
		// 		$wheres['user.sector_id'] = array('in' , $sidArr);
		// 	}
		// }
		if(-1 != $sector) {
			$sidArr = $this->getsubSector( $sector );
			$wheres['user.sector_id'] = array('in' , $sidArr);
		}

		if(-2!=$status){
			$wheres['user.state'] = array('eq', $status );
		}
		$subQuery = M('hr_education')->group('user_id')->order('edu_edate desc')->select(false);
		// dump($subQuery);
		$cnt = $Mdo->where( $wheres )
			   ->join('LEFT JOIN role on role.role_id = user.role_id')
			   ->join('LEFT JOIN user_extension e on e.user_id = user.user_id')
			   ->join('LEFT JOIN hr_education h on h.user_id = user.user_id')
			   ->join('LEFT JOIN sector on sector.sector_id=user.sector_id')
			   ->count();
			   // dump($cnt);
		$Page = new \Common\ORG\Page( $cnt, $psize );
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		/*$ulist = $Mdo->field("user.*,user.login_name,user.nickname,user.sector_id,user.role_id,user.phone,user.qq,user.weixin,user.email,user.state,user.last_time,user.sex,e.ext_name as ename,e.ext_yggh as eyggh,e.ext_xl as exl,e.ext_zzmm as ezzmm,e.ext_user_status as estatus,e.ext_sh_status as eshzt,h.edu_content as econtent,role.role_name as rname,sector.sector_name as sname")
               ->where( $wheres )
			   ->order('user_id desc')
			   ->join('LEFT JOIN role on role.role_id = user.role_id')
			   ->join('LEFT JOIN user_extension e on e.user_id = user.user_id')
			   ->join('LEFT JOIN hr_education h on h.user_id = user.user_id')
			   ->join('LEFT JOIN sector on sector.sector_id=user.sector_id')
			   ->limit($Page->firstRow.','.$Page->listRows )
			   ->select();*/
		$ulist = $Mdo->field("user.*,e.ext_name as ename,e.ext_yggh as eyggh,e.ext_xl as exl,e.ext_zzmm as ezzmm,e.ext_user_status as estatus,e.ext_sh_status as eshzt,h.edu_content as econtent,role.role_name as rname,sector.sector_name as sname")
               ->where( $wheres )
			   ->order('user_id desc')
			   ->join('LEFT JOIN role on role.role_id = user.role_id')
			   ->join('LEFT JOIN user_extension e on e.user_id = user.user_id')
			   ->join('LEFT JOIN ('.$subQuery.') h on h.user_id = user.user_id')
			   ->join('LEFT JOIN sector on sector.sector_id=user.sector_id')
			   ->limit($Page->firstRow.','.$Page->listRows )
			   ->select();
		// dump($ulist);
		if($ulist){
			for( $i = 0; $i < count($ulist); $i ++) {
				$k = 6 - strlen($ulist[$i]['eyggh']);
				for($j = 0 ; $j < $k ;$j ++ ){
					$ulist[$i]['eyggh'] = '0'. $ulist[$i]['eyggh'];
				}
	        } 
	        // $ulist = changeYggh($ulist,eyggh);
		}
		if( $ulist ){
			$res['rcode'] = 1;
			$res['data'] = $ulist;
			$res['pall'] =  $Page->getTotalPages();
			$res['p'] = $Page->nowPage;
			$res['psize'] = $psize;
		}else{
			$res['rcode'] = 2;
			$res['msg'] = "用户记录为空";
		}
		e_json( $res );
	}

	public function getsubSector( $pid ){
		$strList = array();
		if ( $pid > 0 ) {
			$sector = D('Sector');
			$strList = $sector->sub_sector($pid);
		}
			return $strList;
	}

	/*public function changeYggh($list,$va){
		for( $i = 0; $i < count($list); $i ++) {
			$k = 6 - strlen($list[$i]['$va']);
			for($j = 0 ; $j < $k ;$j ++ ){
				$list[$i]['$va'] = '0'. $list[$i]['$va'];
			}
        }
        return $list;
	}*/

	//获取页面操作参数
	public function getPageParam()
	{
		$res = array('rcode'=>1,'sector'=>array(), 'role'=>array(),'msg'=>'','sen'=>'');
		$wheres = array();
		$wheres['is_deleted'] = array('neq', 1);
		$MRole = D('Admin/Role');
		$roles = $MRole->field("role_id,role_name,parent_role")->where( $wheres )->select();
		$_roles = array();
        foreach( $roles as $vs ){
            $_roles[$vs['role_id']] = $vs;
        }
        if( 1 == $this->m_user['user_id'])
	       $arr = list_to_tree($roles,'role_id','parent_role', '_child', 0);
       else{
       		$arr = array();
       		$arr[] = $_roles[$this->m_user['role_id']];
		    $arr[0]['_child'] =  list_to_tree($roles,'role_id','parent_role', '_child', $this->m_user['role_id']);
       }
	   $res['role'] = $arr;
	   $MSector = D('Admin/Sector');
	   $secs = $MSector->field("sector_id,info,sector_name,parent_company,parent_sector,manager_id")->where( $wheres )->select();
       $_secs = array();
	   $arr = array();
    	foreach ($secs as $sc ){
            $_secs[$sc['sector_id']] = $sc;
        }
        if (1 == $this->m_user['user_id']) {
            $arr = list_to_tree($secs,'sector_id','parent_sector','_child', 0 );
        }
        else {
            $arr = array();
            $arr[]=$_secs[$this->m_user['sector_id']];
		    $arr[0]['_child'] = list_to_tree($secs,'sector_id','parent_sector','_child', $this->m_user['sector_id']);
        }
	   $res['sector'] = $arr;
		e_json( $res );
	}
	//根据ID获取用户名
	public function getUserInfoById(){
		$User=M("User");
		$glist = null;
		$wheres = array();
		$p_id = I('get.uid', 0,'intval');
		if( $p_id )
		{
			$wheres['user_id'] = array('eq' , $p_id);
			$glist = $User->field('user_id,login_name,nickname,sector_id,role_id,state,phone,qq,weixin,email')->where($wheres)->select();
			echo json_encode( array("puser"=>array_values($glist)));
		}
		exit();
	}

	//添加新用户
	public function addUser() {
		$MUser=D("User");
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		if (IS_GET) {
			//
		}
		else {
			$addData = array();
			$addData = $_POST['data'];
			$extData = $_POST['ext'];
			
			$UExt  = D('Employee','Model', 'Admin');
			$addres = $UExt->addUser( $addData,$extData );
			if( $addres['r'] ){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
				$res['data'] = $addres['data'];
				$msg = ' '.$addres['data']['userExt']['ext_name'].'，您已成功注册用户，登录名 '.$addres['data']['user']['login_name'].' ，密码 hzhfzx，请尽快登录完善信息。';
				import("Common.ORG.Sentmsg");
				$empSent = new \Common\ORG\Sentmsg();
				$resMsg = $empSent->sent($addData['phone'],$msg);
				$res['sen'] = $resMsg['rcode'];
				//$res['sen'] = 1;
			} else{
				$res['msg'] = $addres['i'];
			}
		}
		e_json( $res );
	}
	//保存编辑用户信息
	public function saveEdit(){
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$MUser=D("Admin/User");
		$UExt = D('Employee','Model', 'Admin');
		if (IS_GET) {
			$uid = I('get.user_id',0, 'intval');
			/*$resl = $UExt->selectUExt($uid);*/
			$uRes = $UExt->getUserById($uid);
			$eRes = $UExt->getUserExtById($uid);
			$resul = array('user'=>$uRes,'userExt'=>$eRes);
			if($resul){
				$res['rcode'] =1;
				$res['msg'] = 'OK';
				// unset($userInfo['pass']);
				$res['data'] = $resul;
			}else{
				$res['msg'] = "客户不存在";
			}
		}
		else {
			$userData = $_POST['user'];
			$emplData = $_POST['empl'];
			$famlyData = $_POST['family'];
			$eduData = $_POST['edu'];
			$trainData = $_POST['train'];
			$workData = $_POST['work'];
			$postExcData = $_POST['postExch'];
			$trainComData = $_POST['trainCom'];
			$uid = $userData['user_id'];

			$UExt->startTrans();
			/*$userRes = M('user')->save( $userData );
			$emplRes = M('user_extension')->where( 'user_id='.$uid )->save( $emplData );*/
			$ueRes = $UExt->saveDecInfo($userData['user_id'],$userData,$emplData);
			$famRes = $UExt->editFamily( $uid ,$famlyData );
			$eduRes = $UExt->editEdu( $uid,$eduData );
			$trainRes = $UExt->editTrain( $uid,$trainData );
			$workRes = $UExt->editWorkExp( $uid,$workData );
			$postExchRes = $UExt->editPostExch( $uid,$postExcData );
			$trainComRes = $UExt->editTrainCom( $uid,$trainComData );

			if( $ueRes['r'] &&  is_numeric($famRes) &&  is_numeric($eduRes) &&  is_numeric($trainRes) &&  is_numeric($workRes) &&  is_numeric($postExchRes) &&  is_numeric($trainComRes) ){
				$UExt->commit();
				$res['rcode'] = 1;
				$res['msg'] = '更新成功';
				$res['data'] = $postExchRes;
			} else{
				$UExt->rollback();
				$res['msg'] = '更新失败';
			}
		}
		e_json( $res );
	}

	//密码重置
	public function resetPass()
	{
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$MUser=D("User");

		if (IS_POST) {
			$user_id = I('post.user_id', 0,'intval');
			$pwd = I('post.pwd', '','trim');
			$ret = $MUser->resetPass( $user_id, $pwd);

			$res['rcode'] = $ret['r'];
			$res['msg'] = $ret['m'];
		}
		e_json( $res );
	}

	//退回修改
	public function returnEdit() {
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$MUserExt=D("user_extension");
		$uid = I('get.user_id', 0 , 'intval');
		// dump($uid);
		$ret = $MUserExt->where('user_id='.$uid)->setField('ext_sh_status',3);
		$reData = M('user')->field("user.phone,user_extension.ext_name")
					->where('user.user_id='.$uid)
					->join('LEFT JOIN user_extension on user.user_id = user_extension.user_id')
					->find();
		if($ret){
			$res['rcode'] = 1;
			$res['msg'] = '已退回修改';
			$msg = ' '.$reData['ext_name'].'，您的CRM资料有误，请尽快修改。';
			import("Common.ORG.Sentmsg");
			$empSent = new \Common\ORG\Sentmsg();
			$resMsg = $empSent->sent($reData['phone'],$msg);
		}else{
			$res['msg'] = '退回处理出错';
		}
		e_json( $res );
	}

	/**
	 * 根据员工姓名获取员工信息
	 *
	 *@return  array  rcode=>0 没有找到员工
	 *                     =>1 唯一员工
	 *                     =>2 员工重名
	 */
	public function searchByName()
	{
		if( IS_POST ){
			$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
			$name = I('post.name','','trim');
			if( !$name ){
				$res['rcode'] = 0;
				$res['msg'] = "提交参数错误";
			}
			else{
				$MUser = D('Admin/User');
				$wheres = $wherelike = array();
				$wheres['nickname'] = array('eq',$name );
				$userfind = $MUser->field("user_id,nickname,sector_id")->where( $wheres )->find();
				$userlike = FALSE;
				if($name ){
					$wherelike['nickname'] = array('like', $name.'%');
					$userlike = $MUser->field("user_id,nickname,sector_id")
									  ->where( $wherelike )
									  ->select();
				}
				if( $userfind || ( $userlike && 1==count( $userlike ) )  ){ //匹配到一个员工
					$res['data'] = $userfind ? $userfind : $userlike[0];
					$res['rcode'] = 1;
				}
				else if( $userlike && 1<count( $userlike) ){ //匹配到多个员工
					$res['rcode'] = 2;
					$res['msg'] = "匹配到多个结果";
				}
				else{
					$res['rcode'] = 0;
					$res['msg'] = "用户匹配失败";
				}
			}
			e_json( $res );
		}
	}

	/*根据客户姓名获取客户信息*/
	public function searchCustomerName() {
		if( IS_POST ){
			$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
			$name = I('post.name','','trim');
			if( !$name ){
				$res['rcode'] = 0;
				$res['msg'] = "提交参数错误";
			}
			else{
				$MCustomer = D('Admin/Customer');
				$wheres = $wherelike = array();
				$wheres['a.nickname'] = array('eq', $name );
				$userfind = M()->field("a.customer_id,a.nickname,a.phone,b.user_id as sales_id,b.nickname as sales_name,c.user_id as sales_manager,c.nickname as manager_name,d.sector_id as sales_company,d.sector_name as subcompany_name")
								->table('customer as a')
								->join('user as b on b.user_id = a.sales_person')
								->join('user as c on c.user_id = a.sales_manager')
								->join('sector as d on d.sector_id = a.sales_sub_company')
								->where( $wheres )
								->find();
				$userlike = FALSE;
				if( strlen($name)>1 ){
					$wherelike['a.nickname'] = array('like', $name.'%');
					$userlike = M()->field("a.customer_id,a.nickname,a.phone,b.user_id as sales_id,b.nickname as sales_name,c.user_id as sales_manager,c.nickname as manager_name,d.sector_id as sales_company,d.sector_name as subcompany_name")
									->table('customer as a')
									->join('user as b on b.user_id = a.sales_person')
									->join('user as c on c.user_id = a.sales_manager')
									->join('sector as d on d.sector_id = a.sales_sub_company')
									->where( $wherelike )
									->find();

				}
				if( $userfind || ( $userlike && 1==count( $userlike ) )  ){ //匹配到一个客户
					$res['data'] = $userfind ? $userfind : $userlike[0];
					$res['rcode'] = 1;
				}
				else if( $userlike && 1<count( $userlike) ){ //匹配到多个客户
					$res['rcode'] = 2;
					$res['msg'] = "匹配到多个结果";
				}
				else{
					$res['rcode'] = 0;
					$res['msg'] = "用户匹配失败";
				}
			}
			e_json( $res );
		}
	}

	public function getEditInfo(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$UExt = D('Employee','Model', 'Admin');
		$uid = I('get.user_id','','trim');
		$contentList = $UExt ->common($uid);
		$contentList['family'] = $UExt->getHrFamById($uid); //家庭成员
		$contentList['education'] = $UExt->getHrEduById($uid); //教育经历
		$contentList['train'] = $UExt->getHrTraById($uid); //培训经历
		$contentList['workexp'] = $UExt->getGongzuoById($uid); //工作经历
		$contentList['postExch'] = $UExt->getHrPosById($uid); //岗位异动
		$contentList['trainCom'] = $UExt->getHrTraComById($uid); //入司培训
		if($contentList){
			$res['rcode'] = 1;
			$res['data'] = $contentList;
		}else{
			$res['msg'] == '获取信息失败';
		}
		e_json( $res );
	}

	public function getShowInfo(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$UExt = D('Employee','Model', 'Admin');
		$uid = I('get.user_id','','trim');
		$contentList = $UExt ->common($uid);
		$contentList['family'] = $UExt->getHrFamById($uid); //家庭成员
		$contentList['education'] = $UExt->getHrEduById($uid); //教育经历
		$contentList['train'] = $UExt->getHrTraById($uid); //培训经历
		$contentList['workexp'] = $UExt->getGongzuoById($uid); //工作经历
		$contentList['postExch'] = $UExt->getHrPosById($uid); //岗位异动
		$contentList['trainCom'] = $UExt->getHrTraComById($uid); //入司培训
		$contentList['commend'] = $UExt->getHrCommById($uid); //嘉奖记录
		$contentList['punish'] = $UExt->getChufaById($uid); //处罚记录
		$contentList['offer'] = $UExt->getHrOffById($uid); //特殊贡献
		// $contentList['dimis'] = $UExt->getDimisById($uid); //离职
		if($contentList){
			$res['rcode'] = 1;
			$res['data'] = $contentList;
		}else{
			$res['msg'] == '获取信息失败';
		}
		e_json( $res );
	}
	
}

?>
